dojo.provide("uws.Tree");

dojo.require("uws.Data");
dojo.require("dijit.Tree");

var tree=null;

//instantiate the tree
function buildNavTree(){
    var treeModel = new dijit.tree.TreeStoreModel({
        store: dataStore,
        query: {name:'*'}
    });
	
	dataStore.fetchItemByIdentity({
		identity:'project',
		onItem:function(item){
			root = item;
			prepareDrawingModule();
		},
		onError:function(error){
			console.dir(error);
		}
	});
	
	dojo.byId("navigation").innerHTML="<div id='treeDiv'></div>";
	
	tree = new dijit.Tree({
		model: treeModel
    }, "treeDiv");
	
	dijit.byId("treeContextMenu").bindDomNode(tree.domNode);
	
	dojo.connect(tree, "onClick", function(item){
		if(isMobile==1){			//if it is mobile, execute a double click
			if(dataStore.getValue(item, "id")=="project"){
				newDiagram();
			}else if(dataStore.getValue(item, "uwstype")=="diagram"){
				surfaceManager.openSurface(item);
			}else if(dataStore.getValue(item, "uwstype")=="component"){
				
			}
		}
	});
	
	//open context menu on right click
	dojo.connect(dijit.byId("treeContextMenu"), "_openMyself", tree, function(e){
		var menu = dijit.byId("treeContextMenu");
		var children = menu.getDescendants();
		var node = dijit.getEnclosingWidget(e.target);		//node in the tree
		var item = node.item;
		
		dojo.forEach(children,function(childitem){
			childitem.domNode.style.display="none";
		});
		
		if(item.uwstype == undefined && item.umltype == undefined){
			for(var i=0;i<children.length;i++){
				if(children[i].domNode.className.search("cm-project")>=0){
					children[i].domNode.style.display="";
				}
			}
		}else if(item.uwstype == "diagram"){
			dojo.forEach(children,function(childitem){
				if(childitem.domNode.className.search("cm-diagram")>=0){
					
					if(item.umltype=="sqlerd" && childitem.domNode.className.search("cm-digram-sp-sql")>=0){
						childitem.domNode.style.display="";
						childitem.domNode.onclick=function(){
							generateSQLCreateScript(item.id);
						}
					}else if(item.umltype=="classdiagram" && childitem.domNode.className.search("cm-digram-sp-class")>=0){
						childitem.domNode.style.display="";
						childitem.domNode.onclick=function(){
							generateJavaClasses(item.id);
						}
					}else if(childitem.domNode.className.search("cm-digram-sp")>=0){
						//ignore
					}else{
						childitem.domNode.style.display="";
						childitem.domNode.onclick=null;
						if(childitem.domNode.id=="deleteDiagram"){
							childitem.domNode.onclick=function(){
								if(confirm('Are you sure you want to delete this diagram?')){
									surfaceManager.destroyItem(item.id,false);
								}
							}
						}else if(childitem.domNode.id=="saveAsSVG"){
							childitem.domNode.onclick=function(){
								saveAsSVG(surfaceManager.getSurface(dataStore.getValue(item, "id")));
							}
						}else if(childitem.domNode.id=="openDiagram"){
							surfaceManager.openSurface(item);
						}else if(childitem.domNode.id=="propertiesDiagram"){
							childitem.domNode.onclick=function(){
								surfaceManager._publishProperties(item);
							}
						}
					}
				}
			});
		}else if(item.uwstype == "component"){
			dojo.forEach(children,function(childitem){
				if(childitem.domNode.className.search("cm-component")>=0){
					childitem.domNode.style.display="";
					childitem.domNode.onclick=null;
					
					if(childitem.domNode.id=="deleteComponent"){
						childitem.domNode.onclick=function(){
							if(confirm('Are you sure you want to delete this component?')){
								componentManager.destroyItem(dataStore.getValue(item, "id"));
							}
						}
					}else if(childitem.domNode.id=="propertiesComponent"){
						childitem.domNode.onclick=function(){
							componentFocusManager._publishProperties(item);
						}
					}
				}
			});
		}else{
			console.debug("Tree Context Menu: Unknown type.");
		}
	});
	
	dojo.connect(tree,"onDblClick",null,function(item,treeNode){
		if(item.uwstype == undefined && item.umltype == undefined){
			newDiagram();
		}else if(item.uwstype == "diagram"){
			surfaceManager.openSurface(item);
		}else if(item.uwstype == "component"){
			var component = componentManager.getById(dataStore.getValue("id"));
			componentFocusManager.focus(component);
		}else{
			console.debug("Tree: Unknown type.");
		}
	});
}

//display new diagram dialog box
function newDiagram(label){
	var id = label || generateID("diagram");
	
	diagramTypeDialog = new dijit.Dialog({
		id: 'diagramTypeDialog',
		title: "UML Diagram Type",
		style: "width: 350px",
		execute:function(){
			_newDiagram(id,label);
		}
	});
	
	diagramTypeDialog.set('content', 
		'<form id="diagramTypeForm" action="" onsubmit="return false">'+
			'<br />'+
			'<input type="hidden" name="diagramId" value="'+id+'" >' +
			'<table style="width:100%"><tr>'+
			'<td>Diagram Name</td><td><input type="text" name="diagramName" value="'+id+'" ></td></tr>' +
			'<tr><td>Diagram Type</td>'+
			'<td><select name="diagramType">'+
				'<option value="usecase">Use Case Diagram</option>'+
				'<option value="activity">Activity Diagram</option>'+
				'<option value="classdiagram">Class Diagram</option>'+
				'<option value="sequence">Sequence Diagram</option>'+
				'<option value="sqlerd">SQL ERD</option>'+
			'</select>'+
			'</td></tr></table><br />' +
			'<div class="center">'+
				'<button type="button" onclick="_newDiagram(\''+label+'\')">' +
					'OK' +
				'</button>' +
				'<button type="button" onclick="dijit.byId(\'diagramTypeDialog\').destroy();">' +
					'Cancel' +
				'</button>'+
			'</div>'+
		'</form>'
	);
    diagramTypeDialog.show();
}

//execute new diagram
function _newDiagram(label){
	var form = dojo.byId('diagramTypeForm');
	
	var tab = new dijit.layout.ContentPane({
		id: "tab_"+form.diagramId.value,
		title: form.diagramName.value,
		closable:true
	});
	
	var border = new dijit.layout.BorderContainer({
		width:"100%",
		height:"100%"
	});
	
	if(form.diagramType.value == "usecase"){
		border.addChild(new dijit.layout.ContentPane({
			href: "page_components/usecase_toolbar.html",
			region:"top",
			preload:true
		}));
	}else if(form.diagramType.value == "classdiagram"){
		border.addChild(new dijit.layout.ContentPane({
			href: "page_components/class_toolbar.html",
			region:"top",
			preload:true
		}));
	}else if(form.diagramType.value == "activity"){
		border.addChild(new dijit.layout.ContentPane({
			href: "page_components/activity_toolbar.html",
			region:"top",
			preload:true
		}));
	}else if(form.diagramType.value == "sequence"){
		border.addChild(new dijit.layout.ContentPane({
			href: "page_components/sequence_toolbar.html",
			region:"top",
			preload:true
		}));
	}else if(form.diagramType.value == "sqlerd"){
		border.addChild(new dijit.layout.ContentPane({
			href: "page_components/sqlerd_toolbar.html",
			region:"top",
			preload:true
		}));
	}
	
	border.addChild(new dijit.layout.ContentPane({
		id:"canvas_"+form.diagramId.value,
		region:"center"
	}));
	
	tab.set('content', border);
	
	dijit.byId("tabContainer").addChild(tab);
	surfaceManager.newSurface("canvas_"+form.diagramId.value, form.diagramName.value, form.diagramType.value ,tab, "tab_"+form.diagramId.value);
	dijit.byId('diagramTypeDialog').destroyRecursive();
}

function generateSQLCreateScript(id){
	if(dataStore){
		if(dataStore.isDirty() && id>2){
			alert("Please save the project first.");
			return;
		}
		
		dataStore.fetchItemByIdentity({
			identity: "project",
			scope: this,
			onItem: function(item){
				var db_key = parseInt(dataStore.getValue(item, "db_key"));
				
				if(db_key > 0){
					window.open("ajax/generate_sql.php?id=" + db_key + "&jsonId=" + id);
				}else{
					alert("Please save the project first.");
				}
			}
		});
	}
}

function generateJavaClasses(id){
	if(dataStore){
		if(dataStore.isDirty() && id>2){
			alert("Please save the project first.");
			return;
		}
		
		dataStore.fetchItemByIdentity({
			identity: "project",
			scope: this,
			onItem: function(item){
				var db_key = parseInt(dataStore.getValue(item, "db_key"));
				
				if(db_key > 0){
					window.open("ajax/generate_class.php?id=" + db_key + "&jsonId=" + id);
				}else{
					alert("Please save the project first.");
				}
			}
		});
	}
}

